package com.chooseCourses.servlet.admin;

import com.chooseCourses.dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;

@WebServlet("/AdminAdd")
public class AdminAdd extends HttpServlet {
    public AdminAdd() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Served at: ").append(req.getContextPath());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userAdd = req.getParameter("userAdd");//获取名为userName的参数
        String userPw = req.getParameter("userPw");
        String userName = req.getParameter("userName");
        int userId = Integer.parseInt(req.getParameter("userId"));

        //创建数据库操作对象
        BaseDao baseDao = new BaseDao();
        PreparedStatement ps=null;//创建ps对象，预处理
        String sql = "insert into admin(name,loginId,loginPassword) values(?,?,?)";

        //调用db中的方法
        //添加数据
        try {
            ps = baseDao.getConnection().prepareStatement(sql);
            ps.setString(1, userAdd);
            ps.setString(2, userAdd);
            ps.setString(3, userPw);
            ps.executeUpdate();//执行sql语句
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                baseDao.closeResource(null,ps,null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //PrintWriter out = response.getWriter();
        resp.sendRedirect("admin/adminMes.jsp?userName=" + userName + "&userId=" + userId);
        doGet(req, resp);
    }
}
